package servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *  * 测试生命周期01，指定初始化顺序，第一个被初始化
 *  * 使用注解给Servlet传初始化参数
 */
@WebServlet(urlPatterns = "/life01", initParams = {
        @WebInitParam(name = "setChar", value = "utf-8")
}, loadOnStartup = 1)
public class DemoLife01Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void init() throws ServletException {
        System.out.println("life01 Servlet initialized.");
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 打印执行日志
        System.out.println("life01 servlet service .....");

        //获取ServletConfig
        ServletConfig config = this.getServletConfig();
        //然后通过ServletConfig的getInitParameter方法获取初始化参数
        String encoding = config.getInitParameter("setChar");
        System.out.println("encoding = " + encoding);

//        request.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding(encoding);

        // 获取请求中的name参数值
        String name = request.getParameter("name");

        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("  <head><title>Servlet</title></head>");
        out.println("  <body>");
        out.println("你好，" + name + "，欢迎来到Servlet的世界！");
        out.println("  </body>");
        out.println("</html>");
        out.close();
    }

    @Override
    public void destroy() {
        System.out.println("life01 Servlet destroyed.");
        super.destroy();
    }
}